﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace WorkStation.Frameworks.Core.Wcf
{
    /// <summary>
    /// * WCF服务代理工厂
    /// </summary>
    
    public class ServiceProxyFactory
    {
        protected static ConcurrentDictionary<string, ChannelFactory> FACTORY_DICT = new ConcurrentDictionary<string, ChannelFactory>();

        /// <summary>
        /// * 建立WCF服务代理（以服务接口的实现类名称为终结点名称）
        /// </summary>
        /// <typeparam name="TChannel"></typeparam>
        /// <returns></returns>
        public static TChannel CreateChannel<TChannel>()
        {
            Type type = typeof(TChannel);

            string endpointName = type.Name.Substring(1);

            return ServiceProxyFactory.CreateChannel<TChannel>(endpointName);
        }

        /// <summary>
        /// * 建立WCF服务代理
        /// </summary>
        /// <typeparam name="TChannel">通道类型</typeparam>
        /// <param name="endpointName">终结点名称</param>
        /// <param name="uri">服务地址</param>
        /// <returns></returns>
        public static TChannel CreateChannel<TChannel>(string endpointName, string uri = null) 
        {
            ChannelFactory<TChannel> factory = FACTORY_DICT.GetOrAdd(endpointName, key => new ChannelFactory<TChannel>(endpointName)) as ChannelFactory<TChannel>;

            if (factory != null)
            {
                return uri == null ? factory.CreateChannel() : factory.CreateChannel(new EndpointAddress(uri));
            }
            else
            {
                return default(TChannel);
            }
        }
    }
}
